package com.ken.common.core.exception;


import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.ken.common.core.utils.JsonUtils;
import com.ken.entity.base.protocol.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * sentinel异常统一处理
 */
@Component
@Slf4j
@ConditionalOnClass(BlockExceptionHandler.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class SentinelException implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        log.error("[Sentinel-WebMvc-Exception] - 触发sentinel异常！", e);

        R result = new R();
        //服务器异常码
        result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());

        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            result.setMessage("服务器被限流！");
        } else if (e instanceof DegradeException) {
            result.setMessage("服务器被降级！");
        }

        //输出结果！
        httpServletResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        httpServletResponse.addHeader("Content-Type", "application/json;charset=utf-8;");
        httpServletResponse.getWriter().println(JsonUtils.obj2Json(result));
    }
}
